﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SkillsWizardPageView.xaml.cs" company="WildGums">
//   Copyright (c) 2008 - 2015 WildGums. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------


namespace Orc.Wizard.Example.Wizard.Views
{
    using System;
    using System.Collections;
    using System.Diagnostics;
    using System.DirectoryServices;
    using System.IO;
    using System.Security.AccessControl;
    using System.Windows;
    using Microsoft.Web.Administration;

    public partial class SkillsWizardPageView
    {
        public SkillsWizardPageView()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            ProgressBar1.Maximum = 90;
            ProgressBar1.Value = 0;
            for (int i = 1; i < 4; i++)
            {
                ProgressBar1.Value += 30;
                NewWebSiteInfo siteInfo = GetWeb(i);
                DelFile(siteInfo.WebPath);
                CreateNewWebSite(siteInfo);               
            }
            SetFileRole();
            MessageBox.Show("发布成功");
        }

        public NewWebSiteInfo GetWeb(int num)
        {
            
            switch (num)
            {
                case 1:
                    string hostIP1 = "";
                    string portNum1 = "8088";
                    string descOfWebSite1 ="" ;
                    string commentOfWebSite1 = "www.smop.com";
                    string webPath1 = @"D:\wwwroot\smop";
                    NewWebSiteInfo siteInfo1 = new NewWebSiteInfo(hostIP1, portNum1, descOfWebSite1, commentOfWebSite1, webPath1); ;
                    return siteInfo1;
                case 2:
                    string hostIP2 = "";
                    string portNum2 = "8082";
                    string descOfWebSite2 = "";
                    string commentOfWebSite2 = "smopAppApi";
                    string webPath2 = @"D:\wwwroot\smopAppApi";
                  
                        NewWebSiteInfo siteInfo2 = new NewWebSiteInfo(hostIP2, portNum2, descOfWebSite2, commentOfWebSite2, webPath2); ;
                    return siteInfo2;
                case 3:
                    string hostIP3 = "";
                    string portNum3 = "9011";
                    string descOfWebSite3 = "";
                    string commentOfWebSite3 = "login";
                    string webPath3 = @"D:\wwwroot\login";
                    NewWebSiteInfo siteInfo3 = new NewWebSiteInfo(hostIP3, portNum3, descOfWebSite3, commentOfWebSite3, webPath3);
                    return siteInfo3;
                default:
                    return null;
            }
        }
        string entPath = String.Format("IIS://{0}/w3svc", "localhost");
        /// <summary>
        /// 删除程序池
        /// </summary>
        /// <param name="AppPoolName"></param>
        /// <returns></returns>
        private bool DeleteAppPool(string AppPoolName)
        {
            bool result = false;
            DirectoryEntry appPools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
            foreach (DirectoryEntry getdir in appPools.Children)
            {
                if (getdir.Name.Equals(AppPoolName))
                {
                    try
                    {
                        getdir.DeleteTree();
                        result = true;
                    }
                    catch
                    {
                        result = false;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 检查程序池是否存在
        /// </summary>
        /// <param name="AppPoolName"></param>
        /// <returns></returns>
        private bool IsAppPoolName(string AppPoolName)
        {
            bool result = false;
            DirectoryEntry appPools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
            foreach (DirectoryEntry getdir in appPools.Children)
            {
                if (getdir.Name.Equals(AppPoolName))
                {
                    result = true;
                    DeleteAppPool(AppPoolName);
                    IsAppPoolName(AppPoolName);
                }
            }
            return result;
        }
        /// <summary>
        /// 判断网站是否存在
        /// </summary>
        /// <param name="bindStr"></param>
        /// <returns></returns>
        public bool EnsureNewSiteEnavaible(string bindStr)
        {
            DirectoryEntry ent = GetDirectoryEntry(entPath);
            foreach (DirectoryEntry child in ent.Children)
            {
                if (child.SchemaClassName == "IIsWebServer")
                {
                    if (child.Properties["ServerBindings"].Value != null)
                    {
                        if (child.Properties["ServerBindings"].Value.ToString() == bindStr)
                        {
                            return false;
                        }
                    }
                }
            }
            return true;
        }
        /// <summary>
        /// 获取网站系统里面可以使用的最小的ID。
        /// 这是因为每个网站都需要有一个唯一的编号，而且这个编号越小越好。
        /// 这里面的算法经过了测试是没有问题的。
        /// </summary>
        /// <returns>最小的id</returns>
        public string GetNewWebSiteID()
        {
            ArrayList list = new ArrayList();
            string tmpStr;

            DirectoryEntry ent = GetDirectoryEntry(entPath);
            foreach (DirectoryEntry child in ent.Children)
            {
                if (child.SchemaClassName == "IIsWebServer")
                {
                    tmpStr = child.Name.ToString();
                    list.Add(Convert.ToInt32(tmpStr));
                }
            }
            list.Sort();
            int i = 1;
            foreach (int j in list)
            {
                if (i == j)
                {
                    i++;
                }
            }
            return i.ToString();
        }

        /// <summary>
        /// 创建一个IIS 网站
        /// </summary>
        /// <param name="siteInfo">网站配置信息</param>
        public void CreateNewWebSite(NewWebSiteInfo siteInfo)
        {
            if (!EnsureNewSiteEnavaible(siteInfo.BindString))
            {
               MessageBox.Show("该网站已存在" + Environment.NewLine + siteInfo.BindString);               
            }
            DirectoryEntry rootEntry = GetDirectoryEntry(entPath);
            string newSiteNum = GetNewWebSiteID();
            DirectoryEntry newSiteEntry = rootEntry.Children.Add(newSiteNum, "IIsWebServer");
            newSiteEntry.CommitChanges();
            newSiteEntry.Properties["ServerBindings"].Value = siteInfo.BindString;
            newSiteEntry.Properties["ServerComment"].Value = siteInfo.CommentOfWebSite;
            newSiteEntry.CommitChanges();
            DirectoryEntry vdEntry = newSiteEntry.Children.Add("root", "IIsWebVirtualDir");
            vdEntry.CommitChanges();
            string ChangWebPath = siteInfo.WebPath.Trim();
            vdEntry.Properties["Path"].Value = ChangWebPath;

            vdEntry.Invoke("AppCreate", true); //创建应用程序
            vdEntry.Properties["AccessRead"][0] = true; //设置读取权限
            vdEntry.Properties["AccessWrite"][0] = true;
            vdEntry.Properties["AccessScript"][0] = true; //执行权限
            vdEntry.Properties["AccessExecute"][0] = false;
            vdEntry.Properties["DefaultDoc"][0] = "Login.aspx"; //设置默认文档
            vdEntry.Properties["AppFriendlyName"][0] = "LabManager"; //应用程序名称           
            vdEntry.Properties["AuthFlags"][0] = 1; //0表示不允许匿名访问,1表示就可以3为基本身份验证，7为windows继承身份验证
            vdEntry.CommitChanges();
            //操作增加MIME
            //IISOle.MimeMapClass NewMime = new IISOle.MimeMapClass();
            //NewMime.Extension = ".xaml"; NewMime.MimeType = "application/xaml+xml";
            //IISOle.MimeMapClass TwoMime = new IISOle.MimeMapClass();
            //TwoMime.Extension = ".xap"; TwoMime.MimeType = "application/x-silverlight-app";
            //rootEntry.Properties["MimeMap"].Add(NewMime);
            //rootEntry.Properties["MimeMap"].Add(TwoMime);
            //rootEntry.CommitChanges();

            #region 针对IIS7

            DirectoryEntry getEntity = new DirectoryEntry("IIS://localhost/W3SVC/INFO");
            int Version = int.Parse(getEntity.Properties["MajorIISVersionNumber"].Value.ToString());
            if (Version > 6)
            {
                #region 创建应用程序池

                string AppPoolName = siteInfo.CommentOfWebSite;
                if (!IsAppPoolName(AppPoolName))
                {
                    DirectoryEntry newpool;
                    DirectoryEntry appPools = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
                    newpool = appPools.Children.Add(AppPoolName, "IIsApplicationPool");
                    newpool.CommitChanges();
                }

                #endregion

                #region 修改应用程序的配置(包含托管模式及其NET运行版本)

                ServerManager sm = new ServerManager();
                sm.ApplicationPools[AppPoolName].ManagedRuntimeVersion = "v4.0";
                sm.ApplicationPools[AppPoolName].ManagedPipelineMode = ManagedPipelineMode.Integrated;
                //托管模式Integrated为集成 Classic为经典
                sm.CommitChanges();

                #endregion

                vdEntry.Properties["AppPoolId"].Value = AppPoolName;
                vdEntry.CommitChanges();
            }

            #endregion

            //启动aspnet_regiis.exe程序 
            string fileName = Environment.GetEnvironmentVariable("windir") +
                              @"\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe";
            ProcessStartInfo startInfo = new ProcessStartInfo(fileName);
            //处理目录路径 
            string path = vdEntry.Path.ToUpper();
            int index = path.IndexOf("W3SVC");
            path = path.Remove(0, index);
            //启动ASPnet_iis.exe程序,刷新脚本映射 
            startInfo.Arguments = "-s " + path;
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            Process process = new Process();
            process.StartInfo = startInfo;
            process.Start();
            process.WaitForExit();
            string errors = process.StandardError.ReadToEnd();
            if (errors != string.Empty)
            {
                throw new Exception(errors);
            }


        }


        public DirectoryEntry GetDirectoryEntry(string entPath)
        {
            DirectoryEntry ent = new DirectoryEntry(entPath);
            return ent;
        }
        /// <summary>
        /// 网站配置信息
        /// </summary>
        public class NewWebSiteInfo
        {
            private string hostIP;   // 主机IP
            private string portNum;   // 网站端口号
            private string descOfWebSite; // 网站表示。一般为网站的网站名。例如"www.dns.com.cn"
            private string commentOfWebSite;// 网站注释。一般也为网站的网站名。
            private string webPath;   // 网站的主目录。例如"e:\ mp"
            public NewWebSiteInfo(string hostIP, string portNum, string descOfWebSite, string commentOfWebSite, string webPath)
            {
                this.hostIP = hostIP;
                this.portNum = portNum;
                this.descOfWebSite = descOfWebSite;
                this.commentOfWebSite = commentOfWebSite;
                this.webPath = webPath;
            }
            public string BindString
            {
                get
                {
                    return String.Format("{0}:{1}:{2}", hostIP, portNum, descOfWebSite); //网站标识（IP,端口，主机头值）
                }
            }
            public string PortNum
            {
                get
                {
                    return portNum;
                }
            }
            public string CommentOfWebSite
            {
                get
                {
                    return commentOfWebSite;
                }
            }
            public string WebPath
            {
                get
                {
                    return webPath;
                }
            }
        }

        // <summary>
        /// 设置文件夹权限 处理给EVERONE赋予所有权限
        /// </summary>
        /// <param name="FileAdd">文件夹路径</param>
        public void SetFileRole()
        {
            string FileAdd= @"D:\wwwroot\smopAppApi";

            //获取文件夹信息
            DirectoryInfo dir = new DirectoryInfo(FileAdd);
            //获得该文件夹的所有访问权限
            System.Security.AccessControl.DirectorySecurity dirSecurity = dir.GetAccessControl(AccessControlSections.All);
            //设定文件ACL继承
            InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
            //添加ereryone用户组的访问权限规则 完全控制权限
            FileSystemAccessRule everyoneFileSystemAccessRule = new FileSystemAccessRule("IUSR", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
            //添加Users用户组的访问权限规则 完全控制权限
            FileSystemAccessRule usersFileSystemAccessRule = new FileSystemAccessRule("IIS_IUSRS", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
            bool isModified = false;
            dirSecurity.ModifyAccessRule(AccessControlModification.Add, everyoneFileSystemAccessRule, out isModified);
            dirSecurity.ModifyAccessRule(AccessControlModification.Add, usersFileSystemAccessRule, out isModified);
            //设置访问权限
            dir.SetAccessControl(dirSecurity);

           // FileAdd = FileAdd.Remove(FileAdd.LastIndexOf('\\'), 1);
          //  DirectorySecurity fSec = new DirectorySecurity();
          //  fSec.AddAccessRule(new FileSystemAccessRule("IUSR", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
           // fSec.AddAccessRule(new FileSystemAccessRule("IIS_IUSRS", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
          //  System.IO.Directory.SetAccessControl(FileAdd, fSec);
        }

        public static void DelFile(string cfile)
        {
           
                if (!Directory.Exists(cfile))
                {
                    //如果有则删除
                    FileInfo fi = new FileInfo(cfile);
                    //判断文件属性是否只读?是则修改为一般属性再删除
                    if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                    {
                        fi.Attributes = FileAttributes.Normal;
                    }                                        
                }
               
            
           
        }
    }
}